import time

import win32gui
import win32print
import win32con
import win32gui, win32com.client, pythoncom
import sys
import ctypes
from PIL import ImageGrab
from math import sin, cos

from utils.config import config
from utils.log import log

# 将程式窗口设为前台
def set_forground():
    try:
        pythoncom.CoInitialize()
        shell = win32com.client.Dispatch("WScript.Shell")
        if getattr(sys, 'frozen', False):
            shell.SendKeys(" ")  # Undocks my focus from Python IDLE
        else:
            shell.SendKeys("")
        # 窗口句柄
        my_whd = win32gui.FindWindow(config.my_wdh_class, config.my_wdh)
        win32gui.SetForegroundWindow(my_whd)
        return my_whd
    except:
        pass

'''窗口工具'''
class WHDUtils():
    def __init__(self):
        self.my_whd = set_forground() # 将窗口句柄置前并保存
        self.load_cur_whd() # 载入最新窗口
    
    # 载入当前窗口
    def load_cur_whd(self):
        try:
            Text = win32gui.GetWindowText(self.my_whd)
            if Text == config.my_wdh:
                time.sleep(1)
                # 窗口句柄处理
                self.x0, self.y0, self.x1, self.y1 = win32gui.GetWindowRect(self.my_whd)
                self.xx = self.x1 - self.x0 # 窗口宽
                self.yy = self.y1 - self.y0 # 窗口高
                self.is_full = self.x0 == 0 and self.y0 == 0 # 是否全屏
                # dpi检测
                dc = win32gui.GetWindowDC(self.my_whd)
                dpi_x = win32print.GetDeviceCaps(dc, win32con.LOGPIXELSX)
                dpi_y = win32print.GetDeviceCaps(dc, win32con.LOGPIXELSY)
                win32gui.ReleaseDC(self.my_whd, dc)
                scale_x = dpi_x / 96
                scale_y = dpi_y / 96
                self.scale = ctypes.windll.user32.GetDpiForWindow(self.my_whd) / 96.0 # 倍率
                log.info("DPI: " + str(self.scale))
                log.info("TEXT: " + str(Text))
                # 计算出真实分辨率
                self.real_width = int(self.xx * scale_x)
                # x01y01:窗口左上右下坐标
                # xx yy:窗口大小
                # scx scy:当前窗口和基准窗口（1920*1080）缩放大小比例
            else:
                log.error("窗口与预设值不一致！已暂停！")
                time.sleep(0.3)
        except:
            time.sleep(0.3)
            pass
    
    # 获取当前窗口截图
    def get_cur_whd_screenshort(self):
        try:
            if self.x0 is None:
                self.load_cur_whd() # 载入最新窗口
            img = ImageGrab.grab((self.x0, self.y0, self.x1, self.y1))
            return img
        except:
            log.error("获取截图失败！")
            pass